package com.java.collection;

 class SimpleLinkedList{
     /**头节点*/
     private Node first;
     /**尾节点*/
     private Node last;
     /**有效元素个数*/
     private int size;
     /**链表中的节点类型*/
     class Node{
         Object element;
         Node pre;
         Node next;
         public Node(Node pre,Object element,Node next){
           this.pre=pre;
           this.element=element;
           this.next=next;
         }
     }
     /**头结点添加元素*/
     public void addFirst(Object element){
         //1.创建新节点
         //1.1获取头节点
         Node f=first;
         //1.2创建新节点,新节点的next节点为first
         Node newNode=new Node(null,element,f);
         //2.设置新节点为first
         first=newNode;
         //3.设置last节点
         if(f==null){
             last=newNode;
         }else{
             f.pre=newNode;
         }
         //4.有效元素个数加1
         size++;
     }
     /**尾结点添加元素*/
     public void addLast(Object element){
         //1.创建新节点
         //1.1获取尾节点
         Node f=last;
         //1.2创建新节点,新节点的next节点为first
         Node newNode=new Node(f,element,null);
         //2.设置新节点为first
         last=newNode;
         //3.设置last节点
         if(f==null){
             first=newNode;
         }else{
             f.next=newNode;
         }
         //4.有效元素个数加1
         size++;
     }

     public String toString(){
         StringBuilder sb=new StringBuilder();
         sb.append("[");
         Node node=first;
         while(node!=null){
             sb.append(node.element).append(",");
             node=node.next;
         }
         if(sb.length()>0)sb.deleteCharAt(sb.length()-1);
         sb.append("]");
         return sb.toString();
     }
}
public class SimpleLinkedListTests{
    public static void main(String[] args) {
        SimpleLinkedList list=new SimpleLinkedList();
        list.addFirst("A");
        list.addFirst("B");
        list.addFirst("C");
        System.out.println(list);
    }
}
